layui.define(['element', 'layer'], function (exports) {

    var $ = layui.$,
        $body = $('body'),
        element = layui.element,
        layer = layui.layer;

    var screen_size = { pc: [1025, -1], pad: [768, 1024], mobile: [0, 767] };
    var aw = $(window).width(), ah = $(window).height();

    var getDevice = function () {
        var width = $(window).width();
        for (var i in screen_size) {
            var sizes = screen_size[i],
                min = sizes[0],
                max = sizes[1];
            if (max == -1) max = width;
            if (min <= width && max >= width) {
                return i;
            }
        }
        return null;
    }

    var isDevice = function (label) {
        return getDevice() == label;
    }

    var isMobile = function () {
        if (isDevice('mobile') || isDevice('pad')) {
            return true;
        }
        return false;
        // return isDevice('mobile');
    }

    var getNod = function (name) {
        var url = location.href,
            reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        if (url.indexOf('?') > -1) {
            var r = url.split('?')[1].match(reg);
            return r != null ? unescape(r[2]) : '';
        }
        return '';
    }

    var Tab = function (el) {
        if (el == 'undefined' || !el) {
            el = 'admintabs';
        }
        this.el = el;
        this.urls = [];
    }

    Tab.fn = Tab.prototype;

    Tab.fn.content = function (src) {
        var iframe = document.createElement("iframe");
        iframe.setAttribute("frameborder", "0");
        iframe.setAttribute("src", src);
        iframe.setAttribute("data-id", this.urls.length);
        return iframe.outerHTML;
    };

    //关闭全部标签时默认第一个
    Tab.fn.init = function () {
        var url = (window.location.hash || '').substring(1);
        if (url.length < 1) {
            return $('.mok-menu [data-load]:first').click();
        }
        // 处理左侧菜单的记忆功能
        var nd = getNod('nds');
        if (nd && nd != 'undefined') {
            var dla = $('.mok-menu li a[data-node=' + nd + ']');
            dla.trigger('click');
        } else {
            var $this = $("#Nav li:eq(0)");
            $this.find('dl.layui-nav-child > dd > a:eq(0)').trigger('click');
            $this.addClass('layui-nav-itemed');
        }
    };

    Tab.fn.is = function (url) {
        return (this.urls.indexOf(url) !== -1)
    };

    Tab.fn.add = function (title, url) {
        if (tabs.is(url)) {
            tabs.change(url);
            return false;
        }
        window.location.hash = url;
        tabs.urls.push(url);
        element.tabAdd(this.el, {
            title: title,
            content: this.content(url),
            id: url
        });
        tabs.change(url);
    };

    Tab.fn.change = function (url) {
        element.tabChange(this.el, url);
    };

    Tab.fn.delete = function (url) {
        element.tabDelete(this.el, url);
    };

    Tab.fn.deleteall = function (urls) {
        $.each(urls, function (i, item) {
            element.tabDelete(this.el, item);
        })
    }

    Tab.fn.onChange = function (callback) {
        element.on('tab(' + this.el + ')', callback);
    };

    Tab.fn.onDelete = function (callback) {
        var self = this;
        element.on('tabDelete(' + this.el + ')', function (data) {
            var i = data.index;
            var url = self.urls[i];
            self.urls.splice(i, 1);
            callback && callback(data);
            var tabitem = $('#appTabs').find('li').length;
            if (tabitem == 0) {
                window.location.hash = '';
                tabs.init();
            } else {
                var item = $('#appTabs').find('li')[tabitem - 1];
                var url = $(item).attr('lay-id');
                var title = $(item).text();
                tabs.add(title, url);
                window.location.hash = url;
            }

        });
    };

    //tab标签
    function rollPage(direction) {
        var $tabTitle = $('#appTabs');
        var left = $tabTitle.scrollLeft();
        if ('left' === direction) {
            $tabTitle.animate({
                scrollLeft: left - 120
            }, 300);
        } else if ('right' === direction) {
            $tabTitle.animate({
                scrollLeft: left + 120
            }, 300);
        }
    }

    //展开和收起
    function slideSideBar() {

        var $slideSidebar = $('.slide-sidebar'),
            $pageContainer = $('.layui-body'),
            $mobileMask = $('.mobile-mask');

        var isFold = false;

        if (isMobile()) {
            // $(".slide-sidebar i").removeClass('layui-icon-spread-right').addClass('layui-icon-spread-left');
            $admin = $body.find('.layui-layout-admin');
            // $admin.addClass('fold-side-bar-xs');
            isFold = true;
            $mobileMask.click(function () {
                $slideSidebar.trigger('click');
            });
        }

        $slideSidebar.click(function (e) {
            e.preventDefault();

            var $this = $(this),
                $icon = $this.find('i'),
                $admin = $body.find('.layui-layout-admin');
            var toggleClass = isMobile() ? 'fold-side-bar-xs' : 'fold-side-bar';//fold-side-bar-xs

            if ($icon.hasClass('layui-icon-spread-right')) {
                $icon.removeClass('layui-icon-spread-right').addClass('layui-icon-spread-left');
                $admin.addClass(toggleClass);
                isFold = true;
                if (isMobile()) $mobileMask.show();
            } else {
                $icon.removeClass('layui-icon-spread-left').addClass('layui-icon-spread-right');
                $admin.removeClass(toggleClass);
                isFold = false;
                if (isMobile()) $mobileMask.hide();
            }
        });

        var tipIndex;
        // 菜单收起后的模块信息小提示
        $('#Nav li > a').hover(function () {
            var $this = $(this);
            if (isFold) {
                tipIndex = layer.tips($this.find('em').text(), $this);
            }
        }, function () {
            if (isFold && tipIndex) {
                layer.close(tipIndex);
                tipIndex = null
            }
        })

    }

    var tabs = new Tab('admintabs'), navItems = [];

    $('#Nav a').on('click', function (event) {
        event.preventDefault();
        // var $this = $(this), url = $this.attr('href'), title = $.trim($this.text());
        var $this = $(this), url = $this.data('load'), title = $.trim($this.text());
        if (url && url !== 'javascript:;' && typeof (url) !== 'undefined') {
            var nds = $this.data('node');
            url = url + (url.indexOf('?') > -1 ? '&' : '?') + 'nds=' + nds;
            if (tabs.is(url)) {
                tabs.change(url);
            } else {
                navItems.push($this);
                tabs.add(title, url);
            }
        } else {
            $this.parents('dl').siblings().find('dd').removeClass('layui-nav-itemed');
        }

    });

    tabs.onChange(function (data) {
        var i = data.index, $this = navItems[i];
        if ($this && typeof $this === 'object') {
            var nds = $this.data('node'), url = $this.data('load');
            $('#Nav dd').removeClass('layui-this');
            $('#Nav dd').removeClass('layui-nav-itemed');
            $this.parent('dd').addClass('layui-this');
            $this.closest('li.layui-nav-item').removeClass('layui-nav-itemed');
            $this.closest('li.layui-nav-item').addClass('layui-nav-itemed').siblings().removeClass('layui-nav-itemed');
            $this.parent().parent().parent().addClass('layui-nav-itemed');
        }
        //每改变一次就刷新一次
        var src = $("#appTabPage").children(".layui-show").find('iframe').attr("src");
        $("#appTabPage").children(".layui-show").find('iframe').attr("src", src);
    });

    tabs.onDelete(function (data) {
        var i = data.index;
        navItems.splice(i, 1);
    });

    slideSideBar();

    //关闭全部标签页 默认打开第一项
    $('body').on('click', '#closeAll', function () {
        // window.location.reload();
        var tabtitle = $("#appTabs li");
        $.each(tabtitle, function (i) {
            tabs.delete($(this).attr("lay-id"));
        })
    });

    //刷新当前
    $('body').on('click', '#freshThis', function () {
        var layId = $("#appTabs").find("li.layui-this").attr('lay-id');
        if (layId) {
            window.location.hash = '#fresh';
            window.location.hash = '#' + layId;
        }
        tabs.onChange(layId);
        var src = $("#appTabPage").children(".layui-show").find('iframe').attr("src");
        $("#appTabPage").children(".layui-show").find('iframe').attr("src", src);
        // tabs.change(layId);
    })

    //关闭当前标签页
    $('body').on('click', '#closeThis', function () {
        var layId = $("#appTabs").find("li.layui-this").attr('lay-id');
        if (layId) {
            tabs.delete(layId);
        }
    });

    //关闭其它标签页
    $('body').on('click', '#closeOther', function () {
        var thisId = $("#appTabs").find("li.layui-this").attr('lay-id');
        if (thisId) {
            $('#appTabs').find('li').each(function (i, o) {
                var layId = $(o).attr('lay-id');
                if (layId != thisId && layId != 0 && layId != '') {
                    tabs.delete(layId);;
                }
            });
        }
    });

    //刷新当前页
    $('body').on('click', '.freshThis', function () {
        var layId = $("#appTabs").find("li.layui-this").attr('lay-id');
        if (layId) {
            window.location.hash = '#fresh';
            window.location.hash = '#' + layId;
        }
        tabs.onChange(layId);
        var src = $("#appTabPage").children(".layui-show").find('iframe').attr("src");
        $("#appTabPage").children(".layui-show").find('iframe').attr("src", src);
        // tabs.change(layId);
    })

    //全屏
    window.fullscreen = function () {
        if (document.fullscreenElement ||
            document.mozFullScreenElement ||
            document.webkitFullscreenElement ||
            document.msFullscreenElement) {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        } else {
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen();
            } else if (document.documentElement.body.msRequestFullscreen) {
                document.documentElement.body.msRequestFullscreen();
            }
        }
    }

    $(".fullscreen").on("click", function () {
        if ($(this).find('a>i').hasClass('layui-icon-screen-full')) {
            $(this).find('a>i').removeClass('ayui-icon-screen-full').addClass('layui-icon-screen-restore');
        } else {
            $(this).find('a>i').removeClass('layui-icon-screen-restore').addClass('ayui-icon-screen-full');
        }
        fullscreen();
    });

    //tab左右移动
    $(".mokui-tab-prev").click(function () {
        rollPage("left");
    });
    $(".mokui-tab-next").click(function () {
        rollPage("right");
    });


    window.openUri = function (title, url, width, height) {

        var mokindex = layer.open({
            type: 2,
            maxmin: true,
            area: [width ? width : 'auto', height ? height : 'auto'],
            title: title || '弹窗',
            content: url,
            skin: 'layui-layer-molv',
            success: function (layero, index) {
                var height = layero.height(), ahs = ah * 0.8;
                if (height > ahs) {
                    layero.find('.layui-layer-content').css('max-height', ahs + 'px');
                    // layero.css('top', (height - ahs) / 2 + 'px').find('.layui-layer-content').css('max-height', ahs + 'px');
                }
            }
        })

    }

    // 默认触发第一个子菜单的点击事件
    var tt = new Tab();
    tt.init(); //初始化
    exports('moktabs', tt);
});